package com.heima.controller.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.controller.Result;
import com.heima.pojo.Partner;
import com.heima.pojo.VendingMachine;
import com.heima.pojo.vo.Dto.PartnerDto;
import com.heima.service.PartnerService;
import com.heima.service.VendingMachineService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;


@Slf4j
@RestController
@RequestMapping("/api/user-service/partner")
public class PartnerController {


    @Autowired
    private PartnerService partnerService;

    @Autowired
    private VendingMachineService vendingMachineService;


    @GetMapping("/search")
    public Result<List<PartnerDto>> findByage(Integer pageIndex, Integer pageSize, String name) {
        log.info("所有的分类分页查询，第{}页，每页{}条", pageIndex, pageSize);
        //健壮性
        if (pageSize == null) {
            pageSize = 10;
        }
        if (pageIndex == null) {
            pageIndex = 1;
        }
        //创建分页对象
        Page<Partner> partner = new Page<>(pageIndex, pageSize);
        //创建lam
        LambdaQueryWrapper<Partner> sqw = new LambdaQueryWrapper<>();
        //模糊查询
        sqw.like(name != null, Partner::getName, name);
        //添加排序规则
        //进行分页查询
        Page<Partner> page = partnerService.page(partner, sqw);
        //新建一个分页对象
        Page<PartnerDto> partnerDto = new Page<>(pageIndex, pageSize);
        //
        //进行基本的复制p
        BeanUtils.copyProperties(partner, partnerDto, "records");
        //获取原来的的数据
        List<Partner> records = page.getRecords();

        List<PartnerDto> newRecordDtos = records.stream().map((record) -> {
            PartnerDto newPartnerDto = new PartnerDto();
            //进行基本的复制
            BeanUtils.copyProperties(record,newPartnerDto);
            //获取开发商的名称
            String name1 = record.getName();

            LambdaQueryWrapper<VendingMachine> qw = new LambdaQueryWrapper<>();
            qw.eq(name1!=null,VendingMachine::getOwnerName,name1);
            int count = vendingMachineService.count(qw);
            newPartnerDto.setVmCount(count);

            return  newPartnerDto;
        }).collect(Collectors.toList());
        return Result.success(newRecordDtos);
    }

}
